package or.dbutils.dao.impl;/*
 *@Author: gjh
 *Date: 2025/2/2620:25
 *Describe:
 */

import or.dbutils.dao.BehaviorDao;
import or.dbutils.entity.Behavior;
import or.dbutils.util.DruidUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class BehaviorDaoImpl implements BehaviorDao {
    QueryRunner qr = new QueryRunner(DruidUtil.getDataSource());

    @Override
    public int insert(Behavior behavior) {
        String sql = "insert into behavior(name,tigger,state) values(?,?,?)";
        Object[] params = {behavior.getName(),behavior.getTigger(),behavior.getState()};
        try {
            return qr.update(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int update(Behavior behavior) {
        String sql = "update behavior set name = ?,tigger = ?,state = ? where id = ?";
        Object[] params = {behavior.getName(),behavior.getTigger(),behavior.getState(),behavior.getId()};
        try {
            return qr.update(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int delete(int id) {
        String sql = "delete from behavior where id = ?";
        Object[] params = {id};
        try {
            return qr.update(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Behavior> selectByPage(int currenPage, int pageSize) {
        String sql = "select * from behavior limit ?,?";
        int limit = (currenPage-1)*pageSize;
        BeanListHandler<Behavior> beanListHandle = new BeanListHandler<>(Behavior.class);
        try {
            return qr.query(sql,beanListHandle,limit,pageSize);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Behavior selectById(int id) {
        String sql = "select * from behavior where id = ?";
        BeanHandler<Behavior> beanHandler = new BeanHandler<>(Behavior.class);
        try {
            return qr.query(sql,beanHandler,id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Behavior> selectAll() {
        String sql = "select * from behavior";
        BeanListHandler<Behavior> beanListHandler = new BeanListHandler<>(Behavior.class);
        try {
            return qr.query(sql, beanListHandler);
        } catch (SQLException e) {
            throw new RuntimeException("查询所有数据失败", e);
        }
    }
}
